import DefaultNavBar from '@/components/StandNavBar/DefaultNavBar';
import Search from '@/components/Search';
import utils from '@/utils';
import { debounce } from '@/utils/helper';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import { ScrollView, View } from '@tarojs/components';
import Taro, { setNavigationBarTitle, useRouter } from '@tarojs/taro';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import './index.scss';
import { ProductItem } from './productItem';
import ProductRecommend from './productRecommend';
import RightBottomCart from './rightBottomCart';
import request from '@/utils/request'
import classNames from 'classnames';

const sortList = [
  { value: 1, label: '新品' },
  { value: 2, label: '销量' },
  { value: 3, label: '价格', switch: true, switchValue: 4 },
];

const SearchType = {
  // 需要关键字搜索
  keywordsRequired: 'keywordsRequired',
  // 展示搜索结果
  search: 'search',
  // 展示 分组, 不带搜索 结果
  group: 'group',
};

// 获取 当前搜索类型
const getSearchType = (searchKeyword, groupId) => {
  // 没有搜索关键字, 且没有 分组ID
  if (!searchKeyword && !groupId) {
    return SearchType.keywordsRequired;
  }

  // 没有搜索关键字, 且存在分组ID
  // 分组商品获取
  if (!searchKeyword && groupId) {
    return SearchType.group;
  }

  // 搜索结果
  return SearchType.search;
};

const pickIdentity = (obj) => {
  let v = { ...obj };

  Object.keys(v).forEach((key) => {
    if (v[key] === undefined || v[key] === null) {
      delete v[key];
    }
  });

  return v;
};

const Products = ({ dispatch, productList, productListFinished, sort }) => {
  return (
    <>
      <ProductItem goodsList={productList} onClick={(product) => {
        utils.goGoodDetail(product, dispatch);
      }} />

      {productListFinished && productList.length > 8 && (
        <View className="end">- 我是有底线的 -</View>
      )}

      {productListFinished && !productList.length && <ProductRecommend sort={sort} />}
    </>
  );
};

const ShopProductFilter = ({
  loading,
  dispatch,
  productGroupList = [],
  productGroupListFinished = false,
  orgSearchProductList,
  orgSearchProductListFinished,
}) => {
  useShowLoading(loading);

  const [currentTab, setCurrentTab] = useState(1);
  const router = useRouter();
  const { params: { groupId,groupName, keywords: inputKeywords } = {} } = router;
  setNavigationBarTitle({
    title:groupName?decodeURIComponent(groupName):'分组商品'
  })
  // 搜索 关键字
  const [searchKeyword, setSearchKeyword] = useState(decodeURIComponent(inputKeywords ?? ''));

  const searchType = getSearchType(searchKeyword, groupId);

  // 搜索的列表, 或者分组列表
  // const productList = searchType === SearchType.group ? productGroupList : orgSearchProductList;
  // const productListFinished =
  // searchType === SearchType.group ? productGroupListFinished : orgSearchProductListFinished;
  const productList = orgSearchProductList;
  const productListFinished = orgSearchProductListFinished;

  const handleTabChanged = (index) => {
    if (sortList[index].switch) {
      setCurrentTab(
        currentTab == sortList[index].value ? sortList[index].switchValue : sortList[index].value,
      );
    } else {
      setCurrentTab(sortList[index].value);
    }
  };

  // 获取下一页数据
  const showNextPageData = debounce(() => {
    getGroupProductList(curCate);
  }, 1200);

  const getGroupProductList = (curCate) => {
    if (searchType === SearchType.keywordsRequired) {
      Taro.showToast({
        title: '请输入关键字',
        duration: 2000,
        icon: 'none',
      });
      return;
    }
    // 关键字搜索
    let data = {
      pageSize: 20,
      sort: 1,
      keywords: searchKeyword
    }
    if(curCate == '0'){
      Object.assign(data,{
        firstGroupId:groupId
      })
    }else{
      Object.assign(data,{
        secondGroupId:curCate
      })
    }
    dispatch({
      type: 'otherApi/fetchOrgSearchProductList',
      payload: pickIdentity(data),
    });

    // if (searchType === SearchType.group) {
    //   dispatch({
    //     type: 'productList/fetchProductGroupList',
    //     payload: pickIdentity({ merchantId, pageSize: 20, sort: currentTab, id: groupId }),
    //   });
    //   return;
    // }

  };

  const handleSearch = (v) => {
    setSearchKeyword(v);
  };

  const handleClear = () => {
    setSearchKeyword('');
  };
  const [cateList,setCateList] = useState([])
  const [curCate,setCurCate] = useState('0')
  useEffect(()=>{
    request({
      url: '/product/product/productReleaseGroup/getProductGroupListByParentId',
      data: {
        parentId:groupId
      },
      method: 'GET'
    }).then(res=>{
      if(res.code == '1'){
        setCateList(res.content)
      }
    })
  },[])

  // 获取商品
  useEffect(() => {
    getGroupProductList(curCate);
  }, [currentTab, searchKeyword]);

  return (
    <>
      {/* <DefaultNavBar title='分组商品' /> */}

      <ScrollView
        className="ShopProductFilter"
        scrollY
        lowerThreshold={240}
        onScrollToLower={showNextPageData}
        style={{
          height: utils.getCalcHeight({ topMenuHeight: false }, 8),
        }}
      >
        <View className="product-search">
          <Search
            handleSearch={handleSearch}
            onClear={handleClear}
            placeholder="搜索商品"
            button={true}
            defaultValue={searchKeyword}
          />
        </View>

        <View className="sortType no-bar">
          {/* <Tabs tabsList={sortList} getCurrentTab={handleTabChanged} /> */}
          <View className={classNames('sort-item',{'customePageStyle':curCate == '0'})} onClick={()=>{setCurCate('0');getGroupProductList('0')}}>全部</View>
          {cateList?.map(res=>{
            return <View className={classNames('sort-item',{'customePageStyle':curCate == res.id})} onClick={()=>{setCurCate(res.id);getGroupProductList(res.id)}}>{res.name}</View>
          })}
        </View>

        <Products
          {...{
            dispatch,
            productList,
            productListFinished,
            sort: currentTab,
          }}
        />

        {/* <RightBottomCart /> */}
      </ScrollView>
    </>
  );
};

export default connect(({ loading, productList, otherApi }) => ({
  loading,
  productGroupList: productList.productGroupList,
  productGroupListFinished: productList.productGroupListFinished,
  productNumInCart: productList.productNumInCart,

  orgSearchProductList: otherApi.orgSearchProductList,
  orgSearchProductListFinished: otherApi.orgSearchProductListFinished,
}))(ShopProductFilter);
